//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    fbstatus: 'none',
    izclist: [],
    // ad1: [],
    // ad2: [],
    Banner: [],
    ADList:[],
    indicatorDots: true,
    autoplay: true,
    interval: 3000,
    duration: 500,
    indicatorColor: 'rgba(0, 0, 0, .6)',
    IsShowCountDown: 0,
    IsShowPic: 0,
    PicUrl: '',
    TipH5Url: '',
    dingshi: 5,
    dingshiDs: 5,

    menuTop: '',
    navbarInitTop: 0,
    isFixed: false,

    changeTuijianIndex: 0,
    tuijianBiaoqian: ['资产处置', '招标拍卖', '供应', '求购'],
    tuijianBiaoqianIndex: 0,
    isLoction: false,
    tuijianTitleHeight: 0,
    intCurrPage: 1, //推荐资产的页数
    city: wx.getStorageSync('isCity'),
    isCityBack: false,
    strProName: '',
    Release: [{
      phone: ''
    }],
    Indexlist: [], //推荐商机列表
    swiperItemCurrent: 0, //轮播列表
    swiperLists: [
      //   {
      //   name: '资产处置合作',
      //   List: [],
      //   tabIndex1: 0,
      //   tabIndex2: 0,
      //   isMore: true,
      //   intCurrPage: 1,
      //   tab: ['资产处置', '招标公告', '供应', '求购']
      // }, 
      {
        name: '推荐',
        List: [],
        tabIndex1: 0,
        tabIndex2: 0,
        isMore: true,
        intCurrPage: 1,
        tab: ['资产处置', '招标拍卖', '供应', '求购']
      }, {
        name: '附近商机',
        List: [],
        tabIndex1: 0,
        tabIndex2: 0,
        isMore: true,
        intCurrPage: 1,
        tab: ['资产处置', '招标拍卖', '供应', '求购']
      }],
    container: null,
    triggered: false, //下拉刷新回弹状态
    scrollenabled: false, //是否开启下拉刷
    showInlet: true,//群入口
    // // =======================app gloable
    // navHeight: app.globalData.navHeight, //导航栏高度
    // navTop: app.globalData.navTop, //导航栏距顶部距离
    // navObj: app.globalData.navObj, //胶囊的高度
    // navObjWid: app.globalData.navObjWid, //胶囊宽度+距右距离
    // tabbarHeight: app.globalData.tabbarHeight, //tabbar高度
    // windowHeight: app.globalData.windowHeight, //窗口高度
    // screenHeight: app.globalData.screenHeight, // 屏幕高度
    // statusBarHeight: app.globalData.statusBarHeight, //状态栏
    // // stickylistHeight: app.globalData.screenHeight - app.globalData.tabbarHeight - app.globalData.statusBarHeight - app.globalData.navHeight -38 -35
    // stickylistHeight: app.globalData.windowHeight - app.globalData.navHeight - 38 - 35 + 10,
    // scrollHetght: app.globalData.windowHeight - app.globalData.navHeight,
    timerIds: [], // 用于存储每个定时器的ID 
    countdownList: [],
    is_sign: 0,
    total: 0,
    read_num: 0,
    FjLoginLog: {},
    matchmakingAlert: false,
    recommendAlert: false,
    reasonsReductionArr: [
      { id: 1, text: '价格过高', isSelected: false },
      { id: 2, text: '不收:废铁', isSelected: false },
      { id: 3, text: '地区太远', isSelected: false },
      { id: 4, text: '处置量太少', isSelected: false },
    ], //选中的减少推荐理由
    reasonsSelectIDArr: [],  //
    selectCellItemData: {},
    linkAlertStatus: 3,//1确认  3 弹窗
    showModal: false,
    LoginUserRankName: '',
    AllLookNum: '',
    HaveLookNum: '',
    NextRankName: '',
    showModalty: false,
    showModaltyContent: '',
    sbtype: 10,
    cityName: '',//定位
    mapKey: 'e24353dac4e7753f2eea4ce5e3112b2d',
    scrollTopY: 0,
    showBack: false
  },

  // 获取当前位置
  getMyLocation: function () {
    var that = this;
    if (!that.data.city) {
      wx.getLocation({
        type: 'wgs84',
        success(res) {
          const latitude = res.latitude
          const longitude = res.longitude
          that.getweizhi(latitude, longitude)
        }
      })
    }
    
  },
  // 获取位置
  getweizhi: function (latitude, longitude) {
    wx.showLoading({
      title: '加载中',
    })
    var that = this;
    wx.request({
      url: `https://restapi.amap.com/v3/geocode/regeo?output=JSON&location=${longitude},${latitude}&key=e24353dac4e7753f2eea4ce5e3112b2d`,
      header: {
        'Content-Type': 'application/json'
      },
      success: function (result) {
        wx.hideLoading()
        console.log('高德result==', result)
        that.setData({
          provName: result.data.regeocode.addressComponent.province,
          cityName: result.data.regeocode.addressComponent.city,
          city: result.data.regeocode.addressComponent.city
        })
        that.downScrollRefresh()
      },
      fail: function (res) {
        // that.getFJ_Get_RecListKey();
      }
    })
    // wx.request({
    //   url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=${that.data.mapKey}`,
    //   header: {
    //     'Content-Type': 'application/json'
    //   },
    //   success: function (result) {
    //     wx.hideLoading()
    //     console.log('result==', result)
    //     that.setData({
    //       provName: result.data.result.ad_info.province,
    //       cityName: result.data.result.ad_info.city,
    //       city: result.data.result.ad_info.city
    //     })
    //     that.downScrollRefresh()
    //   },
    //   fail: function (res) {
    //     // that.getFJ_Get_RecListKey();
    //   }
    // })
  },

  navigatorCellClick(e) {
    var item = e.currentTarget.dataset.item
    if (item.is_read !== 1 && this.data.total > 0) {
      var listData = this.data.countdownList;
      listData[e.currentTarget.dataset.index].is_read = 1
      this.setData({
        read_num: this.data.read_num + 1,
        countdownList: listData
      })
    }
  },
  readnumberClick() {
    this.setData({
      total: 0
    })
  },
  //电话联系
  telephoneContact(e) {
    let item = this.data.selectCellItemData;
    if (e) {
      item = e.currentTarget.dataset.item;
    }
    var that = this;
    var FjLoginLog = wx.getStorageSync('FjLoginLog');
    wx.request({
      url: app.data.api_url2 + "v/vip_get_contact/",
      header: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      data: {
        'user_id': FjLoginLog.UID,
        'id': item.id,
        'action': this.data.linkAlertStatus
      },
      method: 'POST',
      success: function (res) { }
    });
    this.cklxfs(item)
  },
  cklxfs: function (item) {
    var that = this;
    if (app.checkFjLogin()) {
      var FjLoginLog = wx.getStorageSync('FjLoginLog')
      app.getDaoPost('api/FeijiuApp/Feijiu_GetZcLxfs_Jm', {
        strUID: FjLoginLog.UID,
        strUpw: FjLoginLog.UPwd,
        strGqid: item.out_post_id,
        strRSA: app.data.strRSA
      }, res => {
        var result = JSON.parse(app.aesDec(res.data.ZcInfo));
        console.log('result=>', result)
        if (result.ErrNum == 111) {
          that.setData({
            LoginUserRankName: result.LoginUserRankName,
            AllLookNum: result.AllLookNum,
            HaveLookNum: result.HaveLookNum,
            NextRankName: result.NextRankName,
            showModal: true,
            selectCellItemData: item
          })
        } else if (result.ErrNum == 11 || result.ErrNum == 1) {
          wx.makePhoneCall({
            phoneNumber: result.Mobile,
          })
        } else {
          that.showModalty('您没有权限查看该联系方式,了解更多请联系客服人员')
        }
      })
      return
    } else {
      wx.navigateTo({ url: '/pages/login/index' });
    }
  },
  showModalty: function (tishi) {
    this.setData({
      showModalty: true,
      showModaltyContent: tishi
    })
  },
  onConfirm: function () {
    this.setData({
      showModal: false
    })
    wx.showToast({
      title: "加载中",
      icon: "loading",
    })
    var that = this
    var FjLoginLog = wx.getStorageSync('FjLoginLog')
    app.getDaoPost('api/FeijiuApp/Feijiu_GetZcLxfsInfo_Jm', {
      strUID: FjLoginLog.UID,
      strUpw: FjLoginLog.UPwd,
      strGqid: that.data.selectCellItemData.out_post_id,
      strRSA: app.data.strRSA,
      platform_type: 4
    }, res => {
      var result = JSON.parse(app.aesDec(res.data.ZcInfo));
      wx.hideToast()
      if (result.ErrNum == 1) {
        console.log(result)
        wx.makePhoneCall({
          phoneNumber: result.Mobile,
        })
      }
    })
  },
  //减少推荐理由事件
  reasonClick(e) {
    this.data.reasonsReductionArr.map(item => {
      item.isSelected = false
    })
    const index = e.currentTarget.dataset.index;
    const item = e.currentTarget.dataset.item
    this.data.reasonsReductionArr[index].isSelected = true
    this.data.reasonsSelectIDArr = [item.id]
    this.setData({
      reasonsReductionArr: this.data.reasonsReductionArr,
      reasonsSelectIDArr: this.data.reasonsSelectIDArr
    })
    /*多选逻辑
    const index = e.currentTarget.dataset.index;
    const item = e.currentTarget.dataset.item
    var updatedList = this.data.reasonsSelectIDArr
    this.data.reasonsReductionArr[index].isSelected = !item.isSelected
    if(this.data.reasonsReductionArr[index].isSelected){
      this.data.reasonsSelectIDArr.push(item.id)
    }else{
      updatedList = this.data.reasonsSelectIDArr.filter(listItem => listItem !== item.id);
    }
    this.setData({
      reasonsReductionArr:this.data.reasonsReductionArr,
      reasonsSelectIDArr:updatedList
    })
    */
  },
  //提交减少推荐理由
  submitRecommendClick(e) {
    var itemId = this.data.selectCellItemData.id
    if (this.data.reasonsSelectIDArr.length <= 0) {
      wx.showToast({
        title: '请选择减少推荐理由',
        icon: 'none'
      })
    } else {
      var that = this;
      var FjLoginLog = wx.getStorageSync('FjLoginLog');
      var choice = that.data.reasonsSelectIDArr[0]
      wx.request({
        url: app.data.api_url2 + "v/vip_mini_low/",
        header: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        data: {
          'user_id': FjLoginLog.UID,
          'id': itemId,
          'choice': choice
        },
        method: 'POST',
        success: function (res) {
          if (res.statusCode == 200) {
            if (res.data.code == 200) {
              var updateList = that.data.countdownList.filter(listitem => listitem.id !== itemId)
              that.setData({
                countdownList: updateList,
                recommendAlert: false
              })
            } else {
              wx.showToast({
                title: res.data.msg,
                icon: 'none'
              })
            }
          }
        }
      });
    }
  },
  //人工撮合
  matchmakingBtnClick(e) {
    if (this.data.matchmakingAlert) {
      this.setData({ matchmakingAlert: !this.data.matchmakingAlert })
      return
    }
    var itemId = e.currentTarget.dataset.item.id
    var that = this;
    var FjLoginLog = wx.getStorageSync('FjLoginLog');
    wx.request({
      url: app.data.api_url2 + "v/vip_mini_film/",
      header: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      data: {
        'user_id': FjLoginLog.UID,
        'id': itemId,
      },
      method: 'POST',
      success: function (res) {
        if (res.statusCode == 200) {
          if (res.data.code == 200) {
            that.setData({ matchmakingAlert: !that.data.matchmakingAlert })
          } else {
            wx.showToast({
              title: res.data.msg,
              icon: 'none'
            })
          }
        }
      }
    });
  },
  //减少推荐
  recommendBtnClick(event) {
    var item = event.currentTarget.dataset.item;
    if (item) {
      var addressArr = item.address.split(" ")
      var categoryArr = item.cate_name.split(" ")
      this.data.reasonsReductionArr[1].text = '不收:' + categoryArr[categoryArr.length - 1]
      this.data.reasonsReductionArr[2].text = '地区太远:' + addressArr[addressArr.length - 1]
      this.setData({
        reasonsReductionArr: this.data.reasonsReductionArr
      })
    }
    this.setData({ recommendAlert: !this.data.recommendAlert, selectCellItemData: item })
  },
  //倒计时出发
  startCountdown() {
    const that = this;
    this.data.countdownList.forEach((item, index) => {
      const timerId = setInterval(() => {
        const nowTime = new Date().getTime();
        var leftTime = new Date(item.next_pub_time).getTime()
        leftTime = leftTime - nowTime;
        if (leftTime > 0) {
          const countdown = Math.ceil(leftTime / 1000); // 倒计时，单位秒  
          const updatedList = that.data.countdownList.map((listItem, listIndex) => {
            if (listItem.id === item.id) {
              var hour = Math.floor(countdown / 3600)
              hour = String(hour).padStart(2, '0'); // 将数字转换为字符串，并在前面填充零直到长度为2  
              var minute = Math.floor(countdown % 3600 / 60)
              minute = String(minute).padStart(2, '0'); // 将数字转换为字符串，并在前面填充零直到长度为2  
              var second = Math.floor(countdown % 3600 % 60)
              second = String(second).padStart(2, '0'); // 将数字转换为字符串，并在前面填充零直到长度为2  
              listItem.isCountdown = true
              return { ...listItem, countdown, hour, minute, second, isCountdown: true };
            }
            return listItem;
          });
          that.setData({ countdownList: updatedList });
        } else {
          clearInterval(timerId); // 清除定时器  
          that.data.countdownList[index].isCountdown = false
          that.setData({ countdownList: that.data.countdownList }); // 从列表中移除已结束的项  
        }
      }, 1000);
      that.data.timerIds.push(timerId); // 将定时器ID存入数组  
    });
  },
  //获取资产处置合作列表数据
  // getAssetCooperationData: function () {
  //   let a = this.data.swiperLists
  //   this.data.timerIds.forEach(timerId => {
  //     clearInterval(timerId);
  //   });
  //   var Indexlist = this.data.swiperLists
  //   if (Indexlist[0].isMore == false) {
  //     wx.hideLoading({
  //       success: (res) => { },
  //     })
  //     return
  //   }
  //   var that = this;
  //   var FjLoginLog = wx.getStorageSync('FjLoginLog');
  //   wx.request({
  //     url: app.data.api_url2 + "v/vip_cooperate_list/",
  //     header: {
  //       'Content-Type': 'application/x-www-form-urlencoded',
  //     },
  //     data: {
  //       'user_id': FjLoginLog.UID,
  //       'pageSize': 10,
  //       'pageNumber': a[0].intCurrPage
  //     },
  //     method: 'POST',
  //     success: function (res) {
  //       wx.hideLoading({
  //         success: (res) => { },
  //       })
  //       if (res.statusCode == 200) {
  //         if (res.data.code == 200) {
  //           var Indexlist = that.data.swiperLists
  //           if (res.data.data.data.length < 10) {
  //             Indexlist[0].isMore = false
  //           }
  //           if (that.data.swiperLists[0].intCurrPage == 1) {
  //             that.setData({
  //               is_sign: res.data.data.is_sign,
  //               countdownList: res.data.data.data,
  //               total: res.data.data.total,
  //               read_num: res.data.data.read_num,
  //               swiperLists: Indexlist
  //             })
  //           } else {
  //             that.setData({
  //               is_sign: res.data.data.is_sign,
  //               countdownList: [...that.data.countdownList, ...res.data.data.data],
  //               total: res.data.data.total,
  //               read_num: res.data.data.read_num,
  //               swiperLists: Indexlist
  //             })
  //           }
  //           that.startCountdown();
  //         } else {
  //           wx.showToast({
  //             title: res.data.msg,
  //             icon: 'none'
  //           })
  //         }
  //       }
  //     }
  //   });
  // },
  //未签约，跳转签约页面
  signingWeb: function () {
    wx.navigateTo({
      url: '../other/otherWeb',
      success: function (res) {
        // 通过 eventChannel 向被打开页面传送数据
        res.eventChannel.emit('acceptDataFromOpenerPage', {
          url: 'https://wap.feijiu.net/zhuanti/zchz/index.aspx',
          // url: 'http://10.10.10.232:8081/zhuanti/zchz/index.aspx',
          pageSrc: 1,
        });
      },
    });
  },
  //修改回收偏好
  changePreference: function () {
    wx.navigateTo({
      url: '/packageB/pages/recyclingPreference/preference',
    });
  },
  //联系专员
  contactSpecialist: function () {
    wx.navigateTo({
      url: '../other/otherWeb',
      success: function (res) {
        // 通过 eventChannel 向被打开页面传送数据
        res.eventChannel.emit('acceptDataFromOpenerPage', {
          url: 'https://wap.feijiu.net/towxmini.html?source=scheme',
          pageSrc: 1,
        });
      },
    });
  },
  //事件处理函数
  bindViewTap: function () {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  towoyaochuzhi: function (e) {

  },
  togongqiuxinxi: function () {
    wx.navigateTo({
      url: '../gongqiuxinxi/index'
    })
  },

  toCompany: function (e) {
    let item = e.currentTarget.dataset.item
    let loginuid = wx.getStorageSync('FjLoginLog').UID
    let parame = {
      lytype: 3,
      aid: item.Aid ? item.Aid: '',
      loginuid: loginuid ? loginuid : "0"
    }
    if (e.currentTarget.dataset.banner) {
      // 如果是轮播图 ， 那就添加埋点
      this.maiDianData(parame) 
    }
    
    console.log('输出URL======',e.currentTarget.dataset.url )
    if (e.currentTarget.dataset.uid != 0) {
      wx.navigateTo({
        url: '../gongqiuxinxi/shangpu?longUID=' + e.currentTarget.dataset.uid
      })
    } 
    
    else {
      var url = e.currentTarget.dataset.url;
      if (url == '25018') {
        wx.navigateTo({
          url: '/packageB/pages/quickRelease/quickIndex/quickIndex',
        })
      } else if (url.substring(0, 20) == 'https://m.feijiu.net' || url.substring(0, 19) == 'http://m.feijiu.net' ||
        url.substring(0, 19) == 'https://s.jupai.net' || url.indexOf('http://10.10.10.232') >= 0 || url.indexOf('https://wap.feijiu.net') >= 0 ||  url.indexOf('https://m.jupai.net') >= 0) {
        var FjLoginLog = wx.getStorageSync('FjLoginLog');
        if (FjLoginLog.UID) {
          wx.navigateTo({
            url: '../other/otherWeb',
            success: function (res) {
              // 通过 eventChannel 向被打开页面传送数据
              res.eventChannel.emit('acceptDataFromOpenerPage', {
                url: url,
                pageSrc: 1
              })
            }
          })
        } else {
          wx.navigateTo({
            url: '../other/web',
            success: function (res) {
              // 通过 eventChannel 向被打开页面传送数据
              res.eventChannel.emit('acceptDataFromOpenerPage', {
                url: url
              })
            }
          })
        }
      }else if (!url)  {
        // 此时不提示，也不做任何操作!!
        console.log('无效果')
      }else {
        wx.showToast({
          title: '此功能仅限app使用',
          icon: 'none'
        }) 
      }
    }
  },
 // 点击添加广告的
  maiDianData(parame) {
    app.getDaoPost('api/FeijiuApp/Feijiu_AddADHit_v2024', parame, r => {
    })
  },



  toHtml5(e) {
    console.log(e)
    let weburl = e.currentTarget.dataset.url
    // console.log(weburl)
    // wx.navigateTo({
    //   url: `../other/web?url=${weburl}`
    // })

    wx.navigateTo({
      url: '../other/web',
      success: function (res) {
        // 通过 eventChannel 向被打开页面传送数据
        res.eventChannel.emit('acceptDataFromOpenerPage', {
          url: weburl
        })
      }
    })
  },
  toSearch: function () {
    wx.navigateTo({
      url: '../search/index'
    })
  },
  zichanchuzhi: function () {
    wx.navigateTo({
      url: '../zichanchuzhi/index'
    })
  },
  zhaobiaogonggao: function (e) {
    // url: 'detailed?uuid=' + e.currentTarget.dataset.code
    console.log('shuc -----',  e.currentTarget.dataset.uuid)
    wx.navigateTo({
      url: '/pages/zhaobiaogonggao/detailed?uuid=' + e.currentTarget.dataset.uuid,
    })
  },
  news: function () {
    wx.navigateTo({
      url: '../news/index'
    })
  },
  baojiayuce: function () {
    wx.navigateTo({
      url: '/packageA/pages/index/index'
    })
  },
  onCancel: function () {
    this.setData({
      showModal: false
    })
  },
  rengongfabu: function () {
    var that = this
    wx.showModal({
      title: '拨打电话发布信息',
      content: '0311-87106666',
      showCancel: true,
      cancelText: '取消',
      cancelColor: '#000000',
      confirmText: '确定',
      confirmColor: '#3CC51F',
      success: (res) => {
        if (res.confirm) {
          wx.makePhoneCall({
            phoneNumber: '0311-87106666'
          })
        }
      }
    })
  },
  zichanfabu: function () {
    if (app.checkFjLogin()) {
      wx.navigateTo({
        url: '../create/zichan'
      })
    } else {
      wx.navigateTo({
        url: '../../pages/login/index'
      });
    }
  },
  gongqiufabu: function (e) {
    if (app.checkFjLogin()) {
      wx.navigateTo({
        url: '../create/gongqiu?shid=' + e.currentTarget.dataset.shid
      })
    } else {
      wx.navigateTo({
        url: '../../pages/login/index'
      });
    }
  },

  onLoad: async function () {
    this.getMyLocation() //获取位置
    // this.queryServicePhone();
    var that = this
    var ag = app.globalData
    var FjLoginLog = wx.getStorageSync('FjLoginLog');
    let a = that.data.swiperLists;
    //定义导航
    that.setData({
      navHeight: ag.navHeight, //导航栏高度
      safebottom: ag.safeArea.bottom,
      navTop: ag.navTop, //导航栏距顶部距离
      navObj: ag.navObj, //胶囊的高度
      navObjWid: ag.navObjWid, //胶囊宽度+距右距离
      tabbarHeight: ag.tabbarHeight, //tabbar高度
      windowHeight: ag.windowHeight, //窗口高度
      screenHeight: ag.screenHeight, // 屏幕高度
      statusBarHeight: ag.statusBarHeight, //状态栏
      // stickylistHeight: ag.screenHeight - ag.tabbarHeight - ag.statusBarHeight - ag.navHeight -38 -35
      stickylistHeight: ag.windowHeight - ag.navHeight - 38 - 35,
      scrollHetght: ag.windowHeight - ag.navHeight,
      FjLoginLog: FjLoginLog,
    }, async () => {

      await that.queryIndex('Feijiu_GetIndex_v2024') //首页
      // await that.queryNewNav() //230601新改版首页
      await this.queryIndexList(0, a[0].tabIndex2) //推荐商机
      await this.queryIndexList(1, a[1].tabIndex2) //附近商机
      // await this.getAssetCooperationData()
    })
    //
    
    

  },

  async queryAd() {
    let that = this
    await app.getDaoPost('api/FeijiuApp/Feijiu_IsShowCZTipNew', '{}', r => {
      if (r.code == 200) {
        console.log(r)
        that.setData({
          IsShowPic: r.data.IsShowPic,
          PicUrl: r.data.PicUrl,
          TipH5Url: r.data.TipH5Url,
          IsShowCountDown: r.data.IsShowCountDown
        })
        if (r.data.IsShowCountDown == 1) {
          var times = 5;
          var i = setInterval(function () {
            times--
            if (times < 0) {
              clearInterval(i)
              that.c_pop();
            } else {
              that.setData({
                dingshi: times
              })
            }
          }, 1300)
        }
      }
    })
  },
  preventTouchMove: function () {
    // body...
  },
  fuwudianhua: function () {
    wx.makePhoneCall({
      phoneNumber: '0311-87106666'
    })
  },
  onCancelty: function () {
    this.setData({
      showModalty: false
    })
  },
  //关闭发布菜单
  shutdownfb: function () {
    this.setData({
      fbstatus: 'none'
    })

  },
  onHide() {
    // console.log('隐藏了')
    this.setData({
      isRelease: false,
      isPhone: false,
      isLoction: false,
      isCityBack: false
    })
  },
  onUnload() {
    this.data.timerIds.forEach(timerId => {
      clearInterval(timerId);
    });
  },
  //点开发布菜单
  openfb: function () {
    this.setData({
      fbstatus: 'block'
    })
  },

  onShareAppMessage: function (options) {
    var that = this;
    var shareObj = {
      title: '',
      path: '/pages/index/index',
      imgUrl: '../../images/zhuanf.png',
    }
    return shareObj;
  },
  sub: function (str, n) {
    var r = /[^\x00-\xff]/g;
    if (str.replace(r, "mm").length <= n) {
      return str;
    }
    var m = Math.floor(n / 2);
    for (var i = m; i < str.length; i++) {
      if (str.substr(0, i).replace(r, "mm").length >= n) {
        return str.substr(0, i) + "...";
      }
    }
    return str;
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: async function () {
    // 自定义tabbar切换
    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        selected: 0
      })
    };
    // queryIndexList()
    var that = this
    let ag = app.globalData
    var FjLoginLog = wx.getStorageSync('FjLoginLog')
    let a = that.data.swiperLists
    console.log(ag)
    //定义导航
    that.setData({
      navHeight: ag.navHeight, //导航栏高度
      navTop: ag.navTop, //导航栏距顶部距离
      navObj: ag.navObj, //胶囊的高度
      navObjWid: ag.navObjWid, //胶囊宽度+距右距离
      tabbarHeight: ag.tabbarHeight, //tabbar高度
      windowHeight: ag.windowHeight, //窗口高度
      screenHeight: ag.screenHeight, // 屏幕高度
      statusBarHeight: ag.statusBarHeight, //状态栏
      // stickylistHeight: ag.screenHeight - ag.tabbarHeight - ag.statusBarHeight - ag.navHeight -38 -35
      stickylistHeight: ag.windowHeight - ag.navHeight - 38 - 35,
      scrollHetght: ag.windowHeight - ag.navHeight,
      FjLoginLog: FjLoginLog,
    })
    that.queryIndex('Feijiu_GetIndex_v2024') //首页
    a[0].List = [];
    a[0].intCurrPage = 1
    a[0].isMore = true
    a[1].List = []
    a[1].intCurrPage = 1
    a[1].isMore = true
    that.queryIndexList(0, a[0].tabIndex2) //推荐商机
    that.queryIndexList(1, a[1].tabIndex2) //附近商机
  },

  onReady() {
    this.setData({
      scrollenabled: true
    })
    this.queryAd() //广告弹窗
    // const query = wx.createSelectorQuery().in(this);
    // query
    //   .select(".layer12")
    //   .boundingClientRect((rect) => {
    //     let height = rect.height;
    //     console.log("height: ", height);
    //   })
    //   .exec();
  },
  c_pop: function () {
    this.setData({
      IsShowPic: 0
    })
  },
  showInletChange: function () {
    this.setData({
      showInlet: false
    })
  },
  /**
   * 监听滚动事件
   */
  onIndexPageScroll: function (e) {
    if (e.detail.scrollTop >= 400) {
      this.setData({
        showBack: true
      })
    } else {
      this.setData({
        showBack: false
      })
    }

    if (this.data.scrollenabled == true && this.data.triggered == true) {
      this.setData({
        triggered: false,
      })
    }
    var scrollTop = e.detail.scrollTop;
    let ding = this.data.navbarInitTop - this.data.navHeight
    // console.log('滑动')
    var isSatisfy = scrollTop >= (this.data.navbarInitTop - this.data.navHeight - 10);
    // console.log(isSatisfy)
    if (this.data.isFixed == isSatisfy) {
      // console.log('end+', this.data.isFixed)
      return false;
    } else {
      this.setData({
        isFixed: isSatisfy,
        // liststyle: `top:${this.data.navHeight}px`,
        // listTowstyle: `top:${this.data.navHeight+this.data.tuijianTitleHeight}px`,
        liststyle: `top:0px`,
        listTowstyle: `top:0px`,
        liststylestick: `margin-top:0rpx;`, //168
        // liststylestick: `top:${(this.data.navHeight)*2}rpx;position: relative;`,
        a: `position: relative;z-index: 9;top:38px`
      });
    }
  },
  // 改版 查询首页
  queryIndex(api) {
    wx.showLoading({
      title: '数据加载中',
    })
    let input = {},
      that = this
    if (wx.getStorageSync('FjLoginLog')) {
      input.LoginUID = wx.getStorageSync('FjLoginLog').UID
    }
    app.getDaoPost(`api/FeijiuApp/${api}`, input, r => {
      // console.log(r, '首页')
      wx.hideLoading({
        success: (res) => { },
      })
      if (r.code == 200) {
        if (r.data.isTagPopup == 1 && wx.getStorageSync('FjLoginLog')) {
          wx.navigateTo({
            url: '/pages/biaoqian/biaoqian',
          })
        }

        let adListFirst = {
          photo:'/images/home/hqfx_bg.png',
        }
       let adlistH = [adListFirst, ...r.data.ADList]
        that.setData({
          ADList: adlistH,
          Banner: r.data.Banner,
          ListIcon: r.data.ListIconTwo,
          ListIconone: r.data.ListIconOne,
          BjNews: r.data.BjNews,
          isTagPopup: r.data.isTagPopup,
          CJsd: r.data.CJsd.map(item => {
            return { ...item, surname: item.xm.charAt(0) }
          })
        }, () => {
          if (that.data.navbarInitTop == 0) {
            const query = wx.createSelectorQuery()
            query.select('#navbar').boundingClientRect((rect) => {
              if (rect && rect.top > 0) {
                var navbarInitTop = rect.top;
                that.data.navbarInitTop = navbarInitTop
                let height = rect.height;
                that.data.tuijianTitleHeight = height
                that.setData({
                  navbarInitTop,
                  tuijianTitleHeight: height
                })
              }
            }).exec();
            // query.select(".layer12")
            //   .boundingClientRect((rect) => {

            //   })
            //   .exec();
          }
        })

      } else {
        wx.showToast({
          title: r.message,
          icon: 'none'
        })
      }
    })
  },
  // 2024 新版头部导航
  queryNewNav() {
    let input = {},
      that = this
    if (wx.getStorageSync('FjLoginLog')) {
      input.LoginUID = wx.getStorageSync('FjLoginLog').UID
    }
    app.getDaoPost('api/FeijiuApp/Feijiu_GetIndex_v2024', input, r => {
      console.log(r, '230601 新版头部导航')
    })
  },
  //商机切换
  changeTuijian(e) {
    if (this.data.cityName == '' && e.currentTarget.dataset.index == 2) {
      this.setData({
        isLoction: true
      })
    }
    this.setData({
      changeTuijianIndex: e.currentTarget.dataset.index,
      swiperItemCurrent: e.currentTarget.dataset.index,
    }, async () => {
      // await this.queryIndexList()
    })
  },
  // 资产 公告 模块切换
  cilckSahngjiTuijian(e) {
    wx.showLoading({})
    let a = this.data.swiperLists,
      indexb = this.data.changeTuijianIndex
      a[indexb].List = []
      a[indexb].tabIndex2 = e.currentTarget.dataset.index
      a[indexb].isMore = true
      a[indexb].intCurrPage = 1

    this.setData({
      // tuijianBiaoqianIndex: e.currentTarget.dataset.index,
      swiperLists: a,
      scrolltop: 0
    }, async () => {
      await this.queryIndexList(this.data.changeTuijianIndex, e.currentTarget.dataset.index)
    })
  },
  completemessage: function completemessage(res) {
    console.log(res, "res");
  },
  clickCell: function () {
    const url = 'api/FeijiuApp/Feijiu_Community_ClickADD'
    const LoginUID = wx.getStorageSync('FjLoginLog').UID ? wx.getStorageSync('FjLoginLog').UID : "0"
    const _this = this
    const click_platform = "4"
    const systemInfo = wx.getSystemInfoSync();
    const click_system = systemInfo.platform === 'ios' ? "2" : "1"
    app.getDaoPostN(url, { LoginUID, click_position: 3, click_platform, click_system }, function (res) {
      console.log("11111111");
    })
  },
  startmessage: function startmessage(res) {
    console.log("000000000");

  },
  //跳转二级页面
  // 会员服务 签到 积分兑换 新手帮助 常见问题 仅限app
  navDetail(e) {
    let goid = e.currentTarget.dataset.goid,
      name = e.currentTarget.dataset.name,
      id = e.currentTarget.dataset.id
    // if (!!goid) {
    //   if (goid == 5) {
    //     wx.navigateTo({
    //       url: `/packageA/pages/otherMainDetail/otherMainDetail?classId=${goid}&name=${name}`,
    //     })
    //   } else {
    //     wx.navigateTo({
    //       url: `/packageA/pages/mainDetail/mainDetail?classId=${goid}&name=${name}`,
    //     })
    //   }
    // } 
    // else  {
    // 物资供应
    if (id == 10) {
      wx.navigateTo({
        url: '../gongqiuxinxi/index?shid=1'
      })
    } else if (id == 15) {
      // 物资求购
      wx.navigateTo({
        url: '../gongqiuxinxi/index?shid=2'
      })
    } else if (id == 5) {
      // 供求信息
      wx.navigateTo({
        url: '../gongqiuxinxi/index'
      })
    } else if (id == 1) {
      // 资产处置
      wx.navigateTo({
        url: '/packageA/pages/zichanchuzhi/index'
      })
    } else if (id == 2) {
      // 招标拍卖
      // wx.reLaunch({
      //   url: '../zhaobiaogonggao/index?GQ_classid=0'
      // })
      wx.navigateTo({
        url: '/pages/zhaobiaogonggao/index?GQ_classid=0',
      })
    } else if (id == 3) {
      // 报价预测
      wx.navigateTo({
        url: '/packageA/pages/index/index'
      })
    } else if (id == 7) {
      wx.setStorageSync('zybd_key', 'zybd_value')
      // wx.switchTab({
      //   url: '/pages/zhaobiaogonggao/index',
      // })
      wx.navigateTo({
        url: '/pages/zhaobiaogonggao/index',
      })
    } else if (id == 4 || id == 9 || id == 14 || id == 16 || id == 8 || id == 13) {
      // 视频卖货，热门视频，推荐视频，中废通指数,自营标的，地区报价，行情分析
      wx.showToast({
        title: '此功能仅限app使用',
        icon: 'none'
      })
    } else if (id == 6) {
      // 废旧金属
      wx.navigateTo({
        url: `/packageA/pages/zichanchuzhi/index?classId=${goid}&name=${name}`
      })
    } else if (id == 11) {
      // 二手设备
      wx.navigateTo({
        url: `/packageA/pages/zichanchuzhi/index?classId=${goid}&name=${name}`
      })
    } else if (id == 12) {
      // 全网标的--默认为拍卖列表
      // wx.switchTab({
      //   url: '/pages/zhaobiaogonggao/index'
      // })
      wx.navigateTo({
        url: '../zhaobiaogonggao/index?GQ_classid=0',
      })
    }
    // else if (id == 14) {
    //   this.setData({
    //     isRelease: true
    //   })
    // } 
    // else if (id == 15) {
    //   wx.navigateTo({
    //     url: '/packageA/pages/mainDetailMore/mainDetailMore',
    //   })
    // }
    // }
  },

  jumpDetail(e) {
    console.log('e===', e)
    var url = e.currentTarget.dataset.url;
    console.log(url)
    if (url.substring(0, 20) == 'https://m.feijiu.net' || url.substring(0, 19) == 'http://m.feijiu.net' || url.substring(0, 19) == 'https://s.jupai.net') {
      wx.navigateTo({
        url: '/pages/other/web',
        success: function (res) {
          // 通过 eventChannel 向被打开页面传送数据
          res.eventChannel.emit('acceptDataFromOpenerPage', {
            url: url
          })
        }
      })
    } else if (url == 25002 || url == 25003) {
      wx.navigateTo({
        url: '/pages/gongqiuxinxi/index',
      })
    } else if (url == 25004) {
      wx.navigateTo({
        url: '/packageA/pages/zichanchuzhi/index',
      })
    } else if (url == 25005) {
      wx.reLaunch({
        url: '/pages/zhaobiaogonggao/index',
      })
    } else if (url == 25006) {
      wx.navigateTo({
        url: '/packageA/pages/index/index',
      })
    } else if (url == 25013) { // 客服热线
      this.queryServicePhone(25013)
      this.setData({
        isPhone: true,
        callindex: 0
      })
    } else if (url == 25017) { //投诉热线
      this.queryServicePhone(25017)
      this.setData({
        isPhone: true,
        callindex: 2
      })
    } else if (url == 25015) {//租赁
      // if (this.data.IsShopVideo != 1) {
      //   app.tishi(this.data.ZuLinMess);
      //   return false;
      // }
      if (app.checkFjLogin()) {
        wx.navigateTo({
          url: '/packageB/pages/leaseRelease/leaseIndex/leaseIndex',
        })
      } else {
        wx.navigateTo({
          url: '/pages/login/index'
        });
      }
    }
    else {
      wx.showToast({
        title: '此功能仅限app使用',
        icon: 'none'
      })
    }
  },

  chooseLoction(e) {
    wx.navigateTo({
      url: '/packageA/pages/choosLoction/choosLoction',
    })
  },
  clickIsLoction() {
    this.setData({
      isLoction: false
    })
  },
  // 查询首页推荐：资产 公告 供应/求购
  async queryIndexList(tabIndex = this.data.changeTuijianIndex, tab2Index = this.data.swiperLists[this.data.changeTuijianIndex].tabIndex2) {
    // if (tabIndex == 0) {
    //   console.log('资产处置请求')
    //   // this.getAssetCooperationData()
    //   return
    // }
    // console.log(tabIndex, tab2Index)
    // wx.showLoading({})
    // console.log('tabIndex===', tabIndex)
    let that = this,
      changeTuijianIndex = tabIndex, //推荐1 附近2
      tuijianBiaoqianIndex = tab2Index, //资产 公告 供求
      postparam = '',

      LoginUID = wx.getStorageSync('FjLoginLog').UID,
      strCity = that.data.city || that.data.cityName, //城市
      strProName = that.data.strProName, //省
      Indexlist = that.data.swiperLists,
      intCurrPage = Indexlist[changeTuijianIndex].intCurrPage, //that.data.intCurrPage
      inupt = { //参数

      }
    // console.log(changeTuijianIndex, tuijianBiaoqianIndex,Indexlist ,'tab1 tab2 查询')
    if (changeTuijianIndex == 0) {
      if (tuijianBiaoqianIndex == 0) {
        postparam = 'Feijiu_Get_Index_TjZCList'
        inupt = {
          LoginUID,
          intCurrPage,
        }
      } else if (tuijianBiaoqianIndex == 1) {
        postparam = 'Feijiu_Get_Index_TjGGList'
        inupt = {
          LoginUID,
          intCurrPage,
        }
      } else if (tuijianBiaoqianIndex == 2) {
        postparam = 'Feijiu_Get_Index_TjGQList'
        inupt = {
          type: 1,
          LoginUID,
          intCurrPage,
        }
      } else if (tuijianBiaoqianIndex == 3) {
        postparam = 'Feijiu_Get_Index_TjGQList'
        inupt = {
          type: 2,
          LoginUID,
          intCurrPage,
        }
      }
    } else if (changeTuijianIndex == 1) {
      if (tuijianBiaoqianIndex == 0) {
        postparam = 'Feijiu_Get_NearbyZCList'
        inupt = {
          strProName, //省名称
          strCity, //	市名称
          intCurrPage: intCurrPage

        }
      } else if (tuijianBiaoqianIndex == 1) {
        postparam = 'Feijiu_Get_NearbyGGList'
        inupt = {
          strProName, //省名称
          strCity, //	市名称
          intCurrPage: intCurrPage

        }
      } else if (tuijianBiaoqianIndex == 2) {
        postparam = 'Feijiu_Get_NearbyGQList'
        inupt = {
          type: 1,
          strProName, //省名称
          strCity, //	市名称
          intCurrPage: intCurrPage
        }
      } else if (tuijianBiaoqianIndex == 3) {
        postparam = 'Feijiu_Get_NearbyGQList'
        inupt = {
          type: 2,
          strProName, //省名称
          strCity, //	市名称
          intCurrPage: intCurrPage
        }
      }
    }
    await app.getDaoPost(`api/FeijiuApp/${postparam}`, inupt, r => {
      console.log(r, '推荐')
      wx.hideLoading({})
      if (r.code == 200) {
        // 判断标题前面显示的标签
        var titleTag;
        var newData = r.data.data.map(i => {
          if (i.tjid > 0) {
            titleTag = 3
          } else if ((i.title || i.name).indexOf('独家') !== -1) {
            titleTag = 2
          } else if ((i.title || i.name).indexOf('个体') !== -1) {
            titleTag = 1
          } else {
            titleTag = ''
          }
          let distance = "待定"
          let timestate = "other"
          if (tuijianBiaoqianIndex == 1) {
            if (i.time) {
              // 当前时间 - 后台返回的时间
              const now = new Date().getTime();
              let newDateStr = i.time
              let distances = now - new Date(newDateStr).getTime()
              let hours = distances / (60 * 60 * 1000) | 0
              if (hours >= 24) {
                // 当前时间 > 后台返回的时间，并且都超过了24小时，那肯定已经结束了
                distance = '已结束'
                timestate = 'yjs'
              } else if (hours >= 0 && hours < 24) {
                // 当前时间 > 后台返回的时间，但是没有超过24小时,状态就代表进行中
                distance = '正在进行'
                timestate = 'jxz'
              } else if (hours >= -24 && hours < 0) {
                // 当前时间 < 后台返回的时间，并且在24小时之内就要到达后台返回的时间
                distance = '即将开拍'
                timestate = 'jjkp'
              } else if (hours < -24) {
                // 局开拍xxx天
                let days = Math.abs((hours / 24) | 0)
                distance = days + '天'
                timestate = 'jkp'
              }

            }
          }
          let arrs = []
          if (i.keyword) {
            let arr = i.keyword.split(',')
            let filteredArr = arr.filter(item => item !== "")
            arrs = filteredArr
          }
          

          return { ...i, fbdate: (i.fbdate || i.time).split('T')[0], keyword: i.keyword !== '' && i.keyword ? arrs : '', titleTag: titleTag, distance: distance, timestate: timestate }
        })

        if (r.data.data.length >= 15) {
          Indexlist[changeTuijianIndex].List = [...Indexlist[changeTuijianIndex].List, ...newData];
          Indexlist[changeTuijianIndex].intCurrPage = Indexlist[changeTuijianIndex].intCurrPage + 1;
          Indexlist[changeTuijianIndex].isMore = true;
          that.setData({
            swiperLists: Indexlist,
          })

        } else if (r.data.data.length < 15) {
          Indexlist[changeTuijianIndex].List = [...Indexlist[changeTuijianIndex].List, ...newData];
          // Indexlist[changeTuijianIndex].intCurrPage =  Indexlist[changeTuijianIndex].intCurrPage;
          Indexlist[changeTuijianIndex].isMore = false;
          that.setData({
            swiperLists: Indexlist,
          })
        } else {
          Indexlist[changeTuijianIndex].List = [...Indexlist[changeTuijianIndex].List, ...newData];
          // Indexlist[changeTuijianIndex].intCurrPage =  Indexlist[changeTuijianIndex].intCurrPage+1;
          Indexlist[changeTuijianIndex].isMore = false;
          that.setData({
            swiperLists: Indexlist,
          })
        }
      } else {
        wx.hideLoading({})
        wx.showToast({
          title: r.message,
        })
      }
    })

  },
  onReachBottom() {
    console.log('===触底')
    // if(){

    // }
  },
  isReleaseClose() {
    this.setData({
      isRelease: false
    })
  },
  swiperListChange(e) { //列表左右滑动
    if (this.data.city == '' && e.detail.current == 1) {
      this.setData({
        isLoction: true
      })
    }
    console.log('e.detail==', e.detail)
    this.setData({
      changeTuijianIndex: e.detail.current, //改变推荐选中状态
      swiperItemCurrent: e.detail.current, //改变轮播图current
    })
  },
  //scroll 触底加载更多
  indexListMore(e) {
    // if (this.data.changeTuijianIndex == 0 && this.data.swiperLists[0].isMore == true) {
    //   this.data.swiperLists[0].intCurrPage = this.data.swiperLists[0].intCurrPage + 1
    //   this.setData({
    //     swiperLists: this.data.swiperLists
    //   })
    //   wx.showLoading({
    //     title: '数据加载中',
    //   })
    //   // this.getAssetCooperationData()
    //   return;
    // } else if (this.data.changeTuijianIndex == 0 && this.data.swiperLists[0].isMore == false) {
    //   return
    // }
    wx.showLoading({
      title: '数据加载中',
    })
    let changeTuijianIndex = this.data.changeTuijianIndex,
      swiperLists = this.data.swiperLists
    if (swiperLists[changeTuijianIndex].isMore == true) {
      this.queryIndexList(changeTuijianIndex, swiperLists[changeTuijianIndex].tabIndex2)
    } else {
      wx.showToast({
        title: '暂时没有更多啦',
        icon: 'none'
      })
    }
  },
  //用户下拉动作
  downScrollRefresh: async function () {
    var that = this;
    that.setData({
      triggered: true,
    })
    await that.queryIndex('Feijiu_GetIndex_v2024') //首页
    let a = this.data.swiperLists
    a[0].List = [];
    a[0].intCurrPage = 1
    a[0].isMore = true
    a[1].List = []
    a[1].intCurrPage = 1
    a[1].isMore = true
    // a[2].List = []
    // a[2].intCurrPage = 1,
    //   a[2].isMore = true
    this.setData({
      swiperLists: a
    }, async () => {
      await this.queryIndexList(0, a[0].tabIndex2) //推荐商机
      await this.queryIndexList(1, a[1].tabIndex2) //附近商机
      // await this.getAssetCooperationData()
    })
    setTimeout(function () {
      that.setData({
        triggered: false,
      })
    }, 1300);
  },
  // 25017投诉 25013客服
  queryServicePhone(types) {
    //   this.setData({
    //     isPhone: true,
    //     callindex: 0
    //   })
    // } else if (url == 25017) { //投诉热线
    //   this.queryServicePhone(25017)
    //   this.setData({
    //     isPhone: true,
    //     callindex: 2
    //   })

    app.getDaoPost('api/FeijiuApp/Feijiu_Get_FJTel', { type: types }, r => {
      if (r.code == 200) {
        this.setData({
          servicePhone: r.data
        })
        if (types == 25017) {
          // 投诉
          this.setData({
            isPhone: true,
            callindex: 2
          })
        } else if (types == 25013) {
          this.setData({
            isPhone: true,
            callindex: 0
          })
        }
      }
    })
  },


  // 调起电话
  // callPhone(e) {
  //   let ph = e.currentTarget.dataset.ph.substring(0, 11)
  //   wx.makePhoneCall({
  //     phoneNumber: ph //仅为示例，并非真实的电话号码
  //   })
  // },
  callPhone(e) {
    let index = e.currentTarget.dataset.index,
      phone = e.currentTarget.dataset.phone
    this.setData({
      callindex: index
    })
    wx.makePhoneCall({
      phoneNumber: phone
    })
  },

  closePhone() {
    this.setData({
      isPhone: false
    })
  },
  //资产处置详情跳转
  zichanchuzhiDetail(e) {
    // console.log(e, '===')
    let uuid = e.currentTarget.dataset.uuid
    wx.navigateTo({
      url: '/packageA/pages/zichanchuzhi/detailed?gqid=' + uuid,
    })
  },
  gongqiufabuDetail(e) {
    let id = e.currentTarget.dataset.gqid
    wx.navigateTo({
      url: '/pages/gongqiuxinxi/detailed?gqid=' + id,
    })
  },
  rengongfabu(e) {
    wx.makePhoneCall({
      phoneNumber: '031187106666' //
    })
  },
  
  hangqingfenxi() {
    // wx.showToast({
    //   title: '请前往Feijiu网APP查看详情',
    //   icon: 'none'
    // })
    wx.navigateTo({
      url: '/packageA/pages/hangqingList/hangqingList',
    })
  },
  containerscrolltoupper(e) {
    // console.log(e, '滚动到底部')
    this.setData({
      isFixed: true,
    });
  },
  backTopClick(e) {
    this.setData({
      scrollTopY: 0,
      scrolltop: 0,
    })
  }
  // containerbinddragging(e) {
  //   // console.log( e.detail.scrollTop, '滑动事件')
  //   var scrollTop = e.detail.scrollTop;
  //   var isSatisfy = scrollTop >= (this.data.navbarInitTop - this.data.navHeight - 15);
  //   // console.log(isSatisfy)
  //   if (this.data.isFixed == isSatisfy) {
  //     return false;
  //   } else {
  //     this.setData({
  //       isFixed: isSatisfy,
  //     });
  //   }
  // }
})